<template>
  <div>
    <el-dialog
      :title="type === 'add' ? '新增菜品' : '编辑菜品'"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
      @close="close"
    >
      <div v-loading="loading" class="app-main-content-box business-store-edit">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="120px"
          prop="icon"
        >
          <el-form-item label="商品名称：" prop="name">
            <el-input v-model="form.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品预览图" prop="icon">
            <div class="cover-img">
              <el-upload
                :limit="3"
                :action="actionUrl"
                :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                :file-list="imgList"
                :before-upload="handleImgBefore"
                :on-success="handleImgSuccess"
                :class="{ hide: hideUpload }"
                multiple
                accept=".jpg,.jpeg,.JPG,.JPEG,.png,.PNG"
                list-type="picture-card"
              >
                <i slot="default" class="el-icon-plus" />
                <div slot="file" slot-scope="{ file }">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  >
                  <span class="el-upload-list__item-actions">
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleImgRemove(file)"
                    >
                      <i class="el-icon-delete" />
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog title="图片预览" :visible.sync="dialogImageVisible">
                <img width="100%" :src="dialogImageUrl" alt>
              </el-dialog>

              <ul class="upload-tips">
                <li>图片要求：</li>
                <li>1.上传的图片限制文件大小限制1MB，仅支持JPG、PNG格式</li>
                <li>2.建议尺寸：<span class="tag_title">800x800像素，最多可上传3张，第一张为主图</span></li>
              </ul>
            </div>
          </el-form-item>

          <el-form-item label="商品类型：">
            <el-input value="赠送商品" :disabled="true" />
          </el-form-item>
          <el-form-item
            label="商品价格："
            prop="price"
            :rules="rules.specPrice"
          >
            <el-input
              v-model="form.price"
              class="priceb"
              placeholder="请输入内容"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>

          <el-button
            class="add-left"
            size="small"
            round
            @click="dialogVisible = false"
          >取消</el-button>
          <el-button
            type="primary"
            size="small"
            round
            @click="addComfim('form')"
          >保存</el-button>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog title="选择赠品" :visible.sync="showChoose" width="50%">
      <div class="choose_content">
        <div class="top_form">
          <div class="left">
            <div class="title">商品名称</div>
            <div class="input">
              <el-input size="medium" placeholder="请输入赠品名称" />
            </div>
          </div>
          <div class="right">
            <el-button size="medium">查询</el-button>
            <el-button size="medium" type="info">重置</el-button>
          </div>
        </div>
        <div class="choose_pro">
          <div class="title">最多选择【10】个</div>
          <div class="table">
            <el-table
              :data="freeList"
              max-height="400"
              border
              style="width: 100%"
            >
              <el-table-column
                prop="name"
                label="赠送商品名称"
                align="center"
              />
              <el-table-column align="center" label="商品主图">
                <template slot-scope="scope">
                  <div class="choose_img">
                    <img :src="`${fileBaseUrl + scope.row.image}`" alt="">
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                width="80"
                label="价格"
                prop="price"
              />
              <el-table-column width="80" align="center" label="选择">
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.isChecked"
                    @change="chooseFreePro($event, scope.row, scope.$index)"
                  >{{
                    scope.row.isChecked == true ? "已选择" : "选择"
                  }}</el-checkbox>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <span slot="footer" class="choose_dialog_footer">
        <pagination-direction
          :config="paginationConfig"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
        />
        <el-button
          type="primary"
          size="mini"
          @click="confirmFreePro()"
        >确 定（已选{{ freeNum }}件）</el-button>
        <el-button size="mini" @click="showChoose = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import {
  addGoods,
  searAllchClassiFication,
  searchAttributes,
  addClassiFication,
  searchGoodsByOne,
  queryFreeList,
  updateGoods
} from '@/views/wcyModule/api/restaurant'
import { validateStrLen, validateMoney } from '@/utils/validate.js'
import { getShopInfo, createShop, updateShop } from '@/api/shop'
export default {
  data() {
    /**
     * 表单校验方法相关
     */
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商品名称'))
      } else if (!validateStrLen(value, 64)) {
        callback(new Error('长度不超过32个汉字或64个字符'))
      } else {
        callback()
      }
    }
    // const validateDesc = (rule, value, callback) => {
    //   if (value === "") {
    //     callback(new Error("请输入商品描述"));
    //   } else if (!validateStrLen(value, 64)) {
    //     callback(new Error("长度不超过32个汉字或64个字符"));
    //   } else {
    //     callback();
    //   }
    // };

    // 金钱校验
    const validateRmb = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入金额'))
      } else if (!validateMoney(value)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
      } else if (value - 999999.99 > 0) {
        callback('超过限额999999.99')
      } else {
        callback()
      }
    }

    return {
      // 配置

      showChoose: false,
      hideUpload: false,
      resolve: null,
      reject: null,
      type: 'add',
      shopId: '',
      goodsId: '',
      chooseForm: {
        keyword: ''
      },
      //  状态
      dialogVisible: false,
      loading: false,
      // 数据
      // type: 'add',
      specificationItem: false,
      itemNum: [],
      optionsOne: [],
      options: [],
      value: '',
      catevalue: '',
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      /**
       * 表单校验字段相关
       */
      rules: {
        // 名称
        name: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        specPrice: [
          {
            required: true,
            validator: validateRmb,
            trigger: ['blur', 'change']
          }
        ]
      },
      loading: false,
      actionUrl: imgUploadUrl,
      uploadHeaders: {},
      form: {
        name: '',
        price: '',
        status: 1
      },
      freeList: [],
      freeNum: 0,
      dialogImageUrl: '',
      dialogImageVisible: false,
      disabled: false,
      imgList: []
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  methods: {
    // 分页sizes改变
    sizesChange(pageSize) {
      this.initData()
    },

    // 分页page改变
    pageChange(page) {
      this.initData()
    },
    handleImgBefore(file) {
      return this.beforeUploadImg(file, this, 1000, 1000, 1)
    },

    handleImgSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.imgList = fileList
        this.hideUpload = this.imgList.length >= 3
        this.$refs.form.clearValidate(['icon'])
      } else {
        this.$message.error(res.msg)
      }
    },

    handleImgRemove(file) {
      this.imgList.forEach((el, index) => {
        if (el.uid == file.uid) {
          this.imgList.splice(index, 1)
        }
      })
      this.hideUpload = this.imgList.length >= 3
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    editData() {
      searchGoodsByOne({
        id: this.goodsId,
        shopId: this.shopId,
        itemType: 'Gift'
      }).then((res) => {
        if (res.code === 0) {
          this.imgList = []
          res.data.price = res.data.specList[0] && res.data.specList[0].name === 'DEFAULT' ? res.data.specList[0].price / 100 : this.form.itemNum = []; const list = res.data.specList; this.specificationItem = true
          res.data.itemImages.split(',').forEach((v) => {
            this.imgList.push({
              response: { code: 0, data: { path: v } },
              url: this.fileBaseUrl + v
            })
          })
          this.form.mgrItemGifts = res.data.mgrItemGifts
          this.shopId = res.data.shopId
          this.form = res.data
          this.$set(this.form, 'price', res.data.price)
        //   console.log(this.form)
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      })
    },

    open(type, id, mid) {
      console.log(id, mid)

      if (type === 'add') {
        this.type = type
        this.shopId = id
        this.specificationItem = false
        this.initData()
      } else if (type === 'edit') {
        this.type = type
        this.goodsId = id
        this.shopId = mid
        this.editData()
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
      this.loading = false
      this.specificationItem = false
      this.form.itemNum = []
      this.form = {
        icon: '',
        name: '',
        desc: '',
        price: '',
        categroy: '',
        cloum: [],
        itemNum: [],
        status: 1
      }
      //  this.$refs.form.resetFields();
      this.$refs.form.clearValidate()
    },

    // 保存添加
    addComfim(form) {
      this.$refs[form].validate((valid) => {
        console.log(valid)
        if (valid) {
          const {
            imgList,
            form: { status, name },
            goodsId,
            shopId
          } = this
          const attrs = []
          const imgStr = []
          if (imgList.length < 1) {
            this.$message.error('请上传商品图片再进行保存')
            return
          }
          // 获取上传的商品图片
          imgList.forEach((e) => {
            if (e.response.code == 0 && e.status == 'success') {
              imgStr.push(e.response.data.path)
            }
          })
          const params = {
            attrs: attrs,
            itemImages: imgStr.toString(),
            imageUrl: imgStr[0],
            itemType: 'GIFT',
            imageName: imgStr[0],
            status,
            name,
            shopId,
            id: goodsId !== '' ? goodsId : '',
            specList: [
              {
                name: 'DEFAULT',
                price: this.$math.mul(this.form.price, 100, 0)
              }
            ]
          }
          console.log(params)

          if (this.type === 'add') {
            addGoods(params).then((res) => {
              if (res.code === 0) {
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve()
                this.close()
              }
            })
          } else {
            console.log(params)
            updateGoods(params).then((res) => {
              if (res.code === 0) {
                this.$notify({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve()
                this.close()
              }
            })
          }
          this.imgList = []
        }
      })
    },

    // 新建分类
    addClassfication() {
      this.$prompt('请输入分类名称', '新建分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          const data = {
            isValid: true,
            name: value,
            shopId: this.shopId,
            title: value
          }
          addClassiFication(data).then((res) => {
            if (res.code === 0) {
              this.initData()
            }
          })
          this.$notify({
            title: '成功',
            message: '新增分类: ' + value,
            type: 'success',
            duration: 2000,
            offset: 40
          })
        })
        .catch(() => {})
    },

    // 获取数据
    initData() {
      searAllchClassiFication(this.shopId).then((res) => {
        this.optionsOne = []
        if (res.code === 0) {
          const params = res.data.row
          params.map((v, i) => {
            this.optionsOne.push({ value: v.name, label: v.name, id: v.id })
          })
        }
      })
      searchAttributes(this.shopId).then((res) => {
        this.options = []
        if (res.code === 0) {
          const list = res.data
          list.map((v, i) => {
            this.options.push({ value: v.name, label: v.name, id: v.id })
          })
        }
      })
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    // 删除规格
    deteleItem(index) {
      this.form.itemNum.splice(index, 1)
      if (this.form.itemNum.length === 0) {
        this.specificationItem = false
      }
    },

    // 添加规格
    addItem() {
      this.$refs.form.clearValidate(['price'])
      this.specificationItem = true
      this.form.itemNum.push({ name: '', price: '' })
    },
    // 删除或者增加规则配置
    addAndDelRule(type, index) {
      if (type == 1) {
        this.tableData[index].ruleList.splice(index, 1)
      } else {
        const newObj = {
          main: 0,
          minor: 0
        }
        this.tableData[index].ruleList.push(newObj)
      }
    },
    // 删除赠品
    deleteFree(index) {
      this.$confirm('是否删除此赠品?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true
      }).then(() => {
        this.tableData.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    // 打开选择赠送弹窗
    // openChoose() {
    //   let {
    //     form: { mgrItemGifts },
    //     shopId,
    //   } = this;
    //   console.log(mgrItemGifts);
    //   queryFreeList({ shopId, itemType: "GIFT" }).then((res) => {
    //     let { row } = res.data;
    //     this.freeList = row;
    //     // if (mgrItemGifts.length > 1) {
    //     //   mgrItemGifts.forEach((element) => {
    //     //     row.forEach((el, index) => {
    //     //       el.id == element.sellgiftId
    //     //         ? this.$set(this.freeList[index], "isChecked", true)
    //     //         : "";
    //     //     });
    //     //   });
    //     // }
    //   });
    //   this.computedFreeNum();
    //   this.showChoose = true;
    // },
    // 计算已经被勾选的赠送商品数量
    computedFreeNum() {
      this.freeNum = 0
      this.freeList.forEach((el) => {
        el.isChecked == true ? this.freeNum++ : ''
      })
    },
    // 赠品勾选事件
    chooseFreePro(e, data, index) {
      this.$set(this.freeList[index], 'isChecked', e)
      this.computedFreeNum()
    },

    // 赠品弹窗确认事件
    // confirmFreePro() {
    //   // mgrItemGifts 商品规则列表
    //   // freeList 赠品列表
    //   let {
    //     freeList,
    //     form: { mgrItemGifts },
    //   } = this;
    //   freeList.forEach((ele, index) => {
    //     if (
    //       mgrItemGifts.every(
    //         (res) => res.sellgiftId != ele.id && ele.isChecked == true
    //       )
    //     ) {
    //       let newObj = {
    //         sellgiftId: ele.id,
    //         sellgiftName: ele.name,
    //         rules: [{ giftNum: 1, itemNum: 1 }],
    //       };
    //       this.form.mgrItemGifts.push(newObj);
    //     }
    //     mgrItemGifts.forEach((el, idx) => {
    //       if (el.sellgiftId == ele.id && ele.isChecked == false) {
    //         this.form.mgrItemGifts.splice(idx, 1);
    //       }
    //     });
    //   });
    //   this.showChoose = false;
    // },

    /**
     * 按钮组
     */
    // 图片上传
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.form.icon = res.data.path
        this.$refs.form.clearValidate(['icon'])
      } else {
        this.$message.error(res.msg)
      }
    },

    // 上传预处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 1000, 1000, 1)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.business-store-edit {
  .el-input,
  .el-textarea {
    width: 70%;
    max-width: 600px;
  }

  .cover-img {
    // display: flex;
    align-items: center;
    .app-uploader-img-plus {
      flex: 0 0 auto;
    }
  }

  .app-uploader-img-plus {
    width: 180px;
    height: 180px;
    .app-uploader-img-plus-icon {
      font-size: 36px;
      color: #8c939d;
      width: 180px;
      height: 180px;
      line-height: 180px;
      text-align: center;
    }
    .avatar {
      width: 180px;
      height: 180px;
      display: block;
    }
  }
  .upload-tips {
    margin: 10px 0px;
    li {
      margin: 5px 0;
      font-size: 14px;
      line-height: 16px;
      color: $dark-font-color;
    }
  }
}
.free_list {
  margin-bottom: 22px;
  overflow: auto;
}
.selectb {
  width: 460px !important;
}
.priceb {
  width: 200px !important;
}
.add-left {
  margin-left: 120px;
  margin-bottom: 22px;
}
.add-item {
  margin-left: -80px;
  margin-bottom: 22px;
}
.ai-p {
  margin-right: 20px;
}
.li-bo {
  margin-bottom: 20px;
}
.rule_list {
  margin-bottom: 10px;
  .rule_input {
    max-width: 120px;
  }
}
.rule_add {
  width: 100%;
  display: flex;
  padding-left: 5px;
}
.choose_dialog_footer {
  width: 100%;
  display: flex;
  justify-content: center;
}
.choose_content {
  .top_form {
    display: flex;
    > .left {
      display: flex;
      align-items: center;
      margin-right: 30px;
      .title {
        font-weight: bold;
        margin-right: 20px;
      }
      .input {
        min-width: 250px;
      }
    }
  }
  .choose_pro {
    margin-top: 20px;
    .title {
      color: #bbbbbb;
      margin-bottom: 20px;
    }
  }
  .choose_img {
    width: 80px;
    height: 80px;
    overflow: hidden;
    margin: 0 auto;
  }
}
/deep/.hide .el-upload--picture-card {
  display: none;
}
</style>
